<?php
class ctrl_weixin extends ctrl_base
{
    private static $dirName = 'weixin';
    private static $access_token = '';
    
    /**
     * @info oauth2.0网页授权验证   $back_url
     * @author Jackie Yang
     * @date 20140706
     */
    public static function oauth(){
        $_SESSION['wx_userinfo'] = array();
        if(empty($_SESSION['wx_userinfo']) && intval($_SESSION['wx_userinfo']['user_id']) <= 0){
            if(!model_weixin::is_weixin()){
                framework_static_function::write_log('is_weixin:'.$_SERVER['HTTP_USER_AGENT'],'weixin');
                self::smarty()->display('error/wx_error.html'); exit;
            }
            $state = $_GET['state'];
            $code = $_GET['code'];
            if(empty($state) || empty($code)){
                //进行初始化oauth第一步验证   并配置返回的url地址
                $_SESSION['wx_userinfo']=array();
                $return_url = HOST_URL."?act=weixin&st=oauth";
                model_oauth::authorize($return_url);
            }
           /*  if($_SESSION['state'] != $state){
                framework_static_function::write_log('oauth 返回 state验证失败'.$_SESSION['state'].'--'.$state,'weixin');
                self::smarty()->display('error/wx_error.html'); exit;
            }
            unset($_SESSION['state']); */
            //第二步 得到openid号
            $openid = model_oauth::second_authorize($code);
            if(empty($openid)){
                framework_static_function::write_log('oauth 授权失败没有拿到返回值openid','weixin');
                self::smarty()->display('error/wx_error.html'); exit;
            }
            //得到用户信息
            $userinfo = model_user::get_userinfo($openid);
            $_SESSION['wx_userinfo'] = $userinfo;
            /* if(intval($_SESSION['wx_userinfo']['user_id']) <= 0){
                framework_static_function::write_log(' $_SESSION["wx_userinfo"]["user_id"] is empty！从java用户体系没有获取到user_id','weixin');
                self::smarty()->display('error/wx_error.html'); exit;
            } */
            if(!empty($_COOKIE['backurl']) ){
                header("Location:".$_COOKIE['backurl']); exit; 
            }else{
                framework_static_function::write_log('backurl is empty！','weixin');
                self::smarty()->display('error/wx_error.html'); exit;
            }
        }else{
            framework_static_function::write_log(' $_SESSION["wx_userinfo"] is not empty！ ctrl_weixin_weixin::oauth()','weixin');
            self::smarty()->display('error/wx_error.html'); exit;
        }
    }
    
    
    
    /**
     * @info 微信主入口
     * @author Jackie Yang
     */
    public static function index(){
        if(self::checkSignature()){
            if(WEIXIN_AUTH){  //开启第一次
                echo $_GET['echostr']; die;
            }
            switch(model_weixin::checkType()){
                //文本消息
                case 'text':
                    $msgText = model_weixin::get_text_msg();//关键关键字回复文本消息
                    $openid = model_weixin::get_from_username();//获取发送消息用户
                    self::auto_reply($msgText,$openid);
                    break;
                //图片消息
                case 'image':
                    self::get_img_msg();
                    break;
                //事件消息
                case 'event':
                    switch(model_event::checkEvent()){
                        //关注
                        case 'subscribe':
                            model_event::subscribe();
                            break;
                        //取消关注
                        case 'unsubscribe':
                            model_event::unsubscribe();
                            break;
                        //自定义菜单响应
                        case 'CLICK':
                        	$event_key = model_event::getEventKey();
                        	model_event::do_menu_click($event_key);
                        	break;
                    }
                    break;
                //其他
                default:
                    '';
                    break;
            }
            
            
        }
    }
    
    /**
     * @info　给微信用户push消息 跑批
     * @author Jackie Yang
     * @date 20140521
     */
   /*  public static function weixin_push(){
        if(!model_weixin::white_ip(WEIXIN_PUSH_IP))
            exit('ip不在白名单');
        set_time_limit(0);
        list($hour, $min) = explode(':', date('H:i'));
        $hour = intval($hour);
        $min = intval($min);
        framework_static_function::write_log('push start','weixin_send');        
        //竞猜结果处理发消息
        do{
            $re = model_weixin_send::jcpre_weixin_push();
            sleep(2);
        }while($re == TRUE);
        framework_static_function::write_log('push jc end','weixin_send'); 
        //发起送红包活动  下午 6点-8点跑批 给微信用户push消息
        if($hour < 18 || $min > 20) die;
        do{
            $res = model_weixin_send::pre_weixin_push();
            sleep(2);
        }while($res == TRUE);
        echo "执行完成";
    } */
    
    /**
     * 微信基础接口验证
     * @author Jackie Yang
     */
    private static function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * @info 获取已关注者的列表，并注册
     * @author Jackie Yang
     * @date 20140512
     */
/*     public static function get_follow_list($next_openid=''){
        if(!model_weixin::white_ip(WEIXIN_SET_IP))
            exit('ip不在白名单');
        set_time_limit(0);
        $url = 'https://api.weixin.qq.com/cgi-bin/user/get?';
        $url .= 'access_token='.model_weixin::get_access_token();
        $url .= '&next_openid='.$next_openid;
        $res = model_weixin::http_post($url, '');
        if($res != false){
            $res = json_decode($res);
            if(!empty($res) && $res != NULL){
                $arr = get_object_vars($res);
                if(!empty($arr['data'])){
                    $openid_arr = get_object_vars($arr['data']);
                    if($arr['count'] > 0  && count($openid_arr['openid']) > 0){
                        foreach($openid_arr['openid'] as $v){
                            model_user::resgiter($v);
                        }
                        sleep(2);
                        self::get_follow_list($arr['next_openid']);
                    }
                }
                exit('执行完成，共'.$arr['total'].'个微信账号');
            }//end if !empty
        }//end if false
    } */
    
    /**
     * @info 微信设置菜单
     * @author Jackie Yang
     */
    public static function set_menu(){
        /*if(!model_weixin::white_ip(WEIXIN_SET_IP))
            exit('ip不在白名单');*/
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?';
        $url .= 'access_token='.model_weixin::get_access_token();
        $tempath = APP_PATH ."/data";
        if (!file_exists($tempath)) {
            framework_static_base::make_dir($tempath);
        }
        $name = 'weixin_set_menu';
        $body = file_get_contents($tempath."/".$name.".conf");
        if(!empty($body) && $body != FALSE){
            $res = model_weixin::http_post($url, $body);
            $info = json_decode($res,true);
            if(empty($info)||isset($info['errcode'])) {
            	if($info['errcode'] == 42001) { //access_token过期
            		$access_token = model_weixin::get_access_token_by_weixin();//重新获取access_token
            		framework_static_function::write_log($access_token,'access_token');
            		self::set_menu();
            	} else {
            		framework_static_function::write_log('设置菜单错误:'.json_encode($info),'weixin');
            		return FALSE;
            	}
            }
            echo ACCESSTOKEN."<br />";
            var_dump($res);
            exit;
        }
        exit('菜单文件未设置');
    }
    
    /**
     * 获取图片消息
     */
    public static function get_img_msg() {
    	$rs = model_weixin::get_img_msg();
    	$postData['message'] = json_encode($rs);
    	
    	$res = model_weixin::http_post(SAVE_IMG_MSG_URL,$postData);//将图片发送给日钢后台
    	framework_static_function::write_log('图片消息数据请求地址:'.SAVE_IMG_MSG_URL,'weixin_message');
    	framework_static_function::write_log('图片消息数据:'.json_encode($postData),'weixin_message');
    	framework_static_function::write_log('接口返回:'.$res,'weixin_message');
    }
    
    /**
     * 根据关键字自动回复消息
     * @param string $keywords 消息文本
     */
	private static function auto_reply($msgText,$openid) {
    	$arrStr = explode("#", $msgText); //用#分割消息，智能识别指令
    	$cmd = $arrStr[0];//指令
    	$contentStr = '';
    	if($cmd == $msgText) { //消息不含"#"或者"#"后面是空字符串
    		$contentStr = model_message::get_msg_by_keyword($msgText);
    	} else {
	    	switch ($cmd) {
	    		case '合同':
	    			$contentStr = self::get_order_info($arrStr[1],$openid);
	    			break;
	    		case '走访':
	    			$contentStr = self::get_presales_record($arrStr[1],$openid);
	    			break;
	    		case '概况':
	    			$contentStr = self::get_company_overview($arrStr[1],$openid);
	    			break;
	    		case '售后':
	    			$contentStr = self::get_aftermarket_reply($arrStr[1],$openid);
	    			break;
	    		default:
	    			$contentStr = model_message::get_msg_by_keyword($msgText);
	    	}
    	}
    	//回复消息
    	$time = time();
    	$textTpl = "<xml>
                      <ToUserName><![CDATA[%s]]></ToUserName>
                      <FromUserName><![CDATA[%s]]></FromUserName>
                      <CreateTime>%s</CreateTime>
                      <MsgType><![CDATA[%s]]></MsgType>
                      <Content><![CDATA[%s]]></Content>
                     </xml>";
    	$msgType = "text";
    	framework_static_function::write_log($msgText.":".$contentStr,"weixin_message");
    	if(!empty($contentStr)) {
    		//$resultStr = sprintf($textTpl, self::$fromUserName, self::$toUserName, $time, $msgType, $contentStr);
    		$resultStr = model_weixin::get_msg_content($textTpl,$msgType, $contentStr);
    		framework_static_function::write_log($resultStr,'weixin');
    	}
    	echo $resultStr;
    	exit;
    }
    /**
     * 根据合同号获取订单信息
     * @param string $agreement_no 合同编号
     */
    private static function get_order_info($agreement_no,$openid) {
    	$userinfo = model_user::get_userinfo($openid);
    	if($userinfo['user_type'] != 1) { //非内部用户
    		return '您好，合同查询服务仅供注册了日钢内部用户的用户使用。';
    	}
    	$data = model_message::get_order_info($agreement_no);
    	if(is_array($data) && count($data) > 0) {
//    		$contentStr = "合同号：".$data['agreement_no']."\r\n";
//    		$contentStr .= "合同量（t）：".$data['agreement_weight']."\r\n";
//    		$contentStr .= "到款金额（元）：".$data['agreement_no']."\r\n";
//    		$contentStr .= "到款日期：".date('Y-m-d',strtotime($data['agreement_date']))."\r\n";
//    		$scheduling = $data['scheduling']==1? '是':'否';
//    		$contentStr .= "是否排产：".$scheduling."\r\n";
//    		$contentStr .= "开始出厂日期/集港日期：".date('Y-m-d',strtotime($data['produce_date']))."\r\n";
//    		$contentStr .= "累计出厂量/集港量（t）：".$data['produce_total_amount']."\r\n";
//    		$contentStr .= "首批离港日期：".date('Y-m-d',strtotime($data['first_date']))."\r\n";
//    		$contentStr .= "预计到达日期（首批）：".date('Y-m-d',strtotime($data['arrive_date']));

            $reg_url = HOST_URL.'/index.php?act=ordersearch&st=orderInfo&id='.$data['order_id'];
            $contentStr = "   您查询的合同购货单位为".$data['sales_customer']."（销售经理：".$data['sales_name']."），<a href='".$reg_url."'>查看合同订单详情</a>。";
    	} else {
    		$contentStr = '未能找到相关合同信息';
    	}
    	return $contentStr;
    }
    /**
     * @author Jackie Yang
     * 售前走访查询
     * @param string $visit_unit 公司名称
     */
    private static function get_presales_record($visit_unit,$openid) {
    	$userinfo = model_user::get_userinfo($openid);
    	if($userinfo['user_type'] != 1) { //非内部用户
    		return '您好，走访查询服务仅供注册了日钢内部用户的用户使用。';
    	}
    	$contentStr = '';
    	$data = model_interview::get_interview_record_from_weixin($openid, $visit_unit,5);
    	$interview_count = count($data);
    	if($interview_count > 0) {
    		$contentStr = $visit_unit."公司，最近".$interview_count."次走访时间：";
    		foreach ($data as $interview_record) {
                $contentStr .= date('Y-m-d',strtotime($interview_record['recevie_date'])).'、';
            }
            $contentStr = trim($contentStr,"、");
            $contentStr .= '，概况：';
            foreach ($data as $interview_record) {
                $contentStr .= $interview_record['recevie_facts'].'、';
            }
            $contentStr = trim($contentStr,"、");

    	} else {
    		$contentStr = '未能找到相关走访记录！';
    	}
    	return $contentStr;
    }
    /**
     * @author Jackie Yang
     * 获取某公司最近一次走访概况
     * @param string $visit_unit
     */
    private static function get_company_overview($visit_unit,$openid) {
    	$userinfo = model_user::get_userinfo($openid);
    	if($userinfo['user_type'] != 1) { //非内部用户
    		return '您好，走访查询服务仅供注册了日钢内部用户的用户使用。';
    	}
    	$contentStr = '';
    	$data = model_interview::get_interview_record_from_weixin($openid, $visit_unit,1);
    	$interview_count = count($data);
    	if($interview_count > 0) {
    		$contentStr = !empty($data[0]['recevie_facts'])? $data[0]['recevie_facts']:'';
    	}else{
            $contentStr = '未能找到相关公司信息';
        }
    	return $contentStr;
    }
    /**
     * @author Jackie Yang
     * 售后查询
     * @param string $customer_name 公司/客户名称
     */
    private static function get_aftermarket_reply($customer_name,$openid) {
    	$userinfo = model_user::get_userinfo($openid);
    	if($userinfo['user_type'] != 1) { //非内部用户
    		return '您好，售后查询服务仅供注册了日钢内部用户的用户使用。';
    	}
    	$contentStr = '';
    	$data = model_interview::get_aftermarket_record($customer_name);

    	if(count($data) > 0 && $data) {
    		if(!empty($data['repeat_content'])) {
    			$contentStr = $data['repeat_content'];
    		} else {
    			$contentStr = '正在处理中，我们会尽快给您答复，请耐心等待，谢谢！';
    		}
    	} else {
    		$contentStr = '未能找到相关售后记录！';
    	}
    	return $contentStr;
    }
}
